﻿using CPPEI.Coolzon.Designtime.Metadata;
using CPPEI.Coolzon.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CPPEI.Coolzon.Designer.UI;
using System.Collections;
using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.Metadata.ParserV1;
using System.Xml.Linq;
using CPPEI.Coolzon.Designer.Event.UI;
using System.ComponentModel;
using CPPEI.Coolzon.UI.Views;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for SolutionView.xaml
    /// </summary>
    public partial class SolutionView : View
    {
        private bool CanContextMenuShow;
        public SolutionView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 场景等选择改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tvSolution_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                if (tvSolution.SelectedItem != null)
                {
                    SolutionTreeViewNode tvNode = tvSolution.SelectedItem as SolutionTreeViewNode;
                    UIContext.Current.CurrentSelectedNode = tvNode;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("SolutionView-tvSolution_SelectedItemChanged,错误:" + ex.Message);
            }
        }

        private void TreeViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var tvi = sender as TreeViewItem;
                if (tvi == null || !tvi.IsSelected)
                    return;

                if (tvSolution.SelectedItem != null)
                {
                    SolutionTreeViewNode tvNode = tvSolution.SelectedItem as SolutionTreeViewNode;
                    UIContext.Current.CurrentSelectedNode = tvNode;
                    if (tvNode.NodeType == NodeType.Scene)
                    {
                        if (UIContext.Current.CurrentEditedNode != null && UIContext.Current.CurrentEditedNode.ID == tvNode.ID)
                        {
                            return;
                        }

                        if (SolutionTreeViewNodeHelper.IsCancelSaveOrUnSaveCurrentSceneOperation())
                        {
                            return;
                        }
                        if (UIContext.Current.CurrentEditedNode != null)
                        {
                            UIContext.Current.CurrentEditedNode.PropertyChanged -= CurrentEditedNode_PropertyChanged;
                        }
                        UIContext.Current.CurrentEditedNode = tvNode;
                        UIContext.Current.CurrentEditedNode.PropertyChanged += CurrentEditedNode_PropertyChanged;
                        if (tvNode.NodeStatus == NodeStatus.CheckIn || tvNode.NodeStatus == NodeStatus.OthersLocked)
                        {
                            UIContext.Current.CurrentDesignView.API_OpenScene(tvNode.Name, false);
                        }
                        else if(tvNode.NodeStatus != NodeStatus.Delete)
                        {
                            UIContext.Current.CurrentDesignView.API_OpenScene(tvNode.Name, true);
                        }
                        else
                        {
                            CustomMessageBox.ShowWarning("场景已删除");
                            return;
                        }
                        if (UIContext.Current.MainView is MainView)
                        {
                            (UIContext.Current.MainView as MainView).SceneTabFocus(tvNode.ID, tvNode.Name);
                        }
                        OperationCenter.Instance.Reset();
                        UIContext.Current.CurrentDesignView.API_Select(null);
                    }
                    else if (tvNode.NodeType == NodeType.Template)
                    {
                        bool IsCheckOut = false;
                        if (tvNode.NodeStatus == NodeStatus.CheckOut || tvNode.NodeStatus == NodeStatus.Add)
                        {
                            IsCheckOut = true;
                        }
                        Template template = SolutionHelper.GetTemplate(UIContext.Current.CurrentSolution, tvNode.ParentID, tvNode.ID);
                        NewTemplateWindow window = new NewTemplateWindow(template, IsCheckOut);
                        window.ShowDialog();
                    }
                    else if (tvNode.NodeType == NodeType.Resource)
                    {
                        ResourceType nodeRType = SolutionTreeViewNodeHelper.GetResourceTypeByExt(tvNode.Extension);
                        string fileName = LocalStorage.GetResourceFileAbsolutePath(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, tvNode.ID, tvNode.Extension);
                        if (UIContext.Current.MainView is MainView)
                        {
                            (UIContext.Current.MainView as MainView).OpenResource(tvNode, fileName, nodeRType);
                        }
                    }
                    else if(tvNode.NodeType == NodeType.StaticDataSource)
                    {
                        string filePath = Designtime.Metadata.LocalStorage.GetStaticDataSourceAbsolutePath(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution.ID, tvNode.ID);
                        StaticDataSourceWindow window = new StaticDataSourceWindow(filePath, tvNode.ID);
                        window.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("SolutionView-tvSolution_MouseDoubleClick,错误:" + ex);
            }
        }

        public static void CurrentEditedNode_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (string.Equals(e.PropertyName, "NodeStatus"))
            {
                SolutionTreeViewNode node = sender as SolutionTreeViewNode;
                if (node.NodeStatus == NodeStatus.CheckOut)
                {
                    UIContext.Current.CurrentDesignView.API_ChangeEditable(node.Name, true);
                }
                else
                {
                    UIContext.Current.CurrentDesignView.API_ChangeEditable(node.Name, false);
                }
            }
        }

        [Obsolete]
        public TreeViewItem SelectItemByRightClickOfMvvm(ItemsControl source)
        {
            if (!(source is TreeView) && !(source is TreeViewItem))
            {
                throw new ArgumentException("只支持参数为TreeView或者TreeViewItem", "source");
            }
            foreach (object item in source.Items)
            {
                TreeViewItem currentItem = source.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                Point mousePosition = Mouse.GetPosition(currentItem);
                Rect itemRect = VisualTreeHelper.GetDescendantBounds(currentItem);
                // 可能是选中的项，也可能是选中项的父节点
                if (itemRect.Contains(mousePosition))
                {
                    // 看看是不是它的孩子被选中了，否则就是它自己被选中了
                    if (currentItem.IsExpanded)
                    {
                        // 只判断展开的项
                        TreeViewItem selectedItem = SelectItemByRightClickOfMvvm(currentItem);
                        if (selectedItem != null)
                        {
                            selectedItem.IsSelected = true;
                            return selectedItem;
                        }
                    }
                    currentItem.IsSelected = true;

                    return currentItem;
                }
            }
            return null;
        }
        private void tvSolution_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
            if (treeViewItem != null)
            {
                treeViewItem.Focus();
                if(SolutionTreeViewNodeHelper.IsStaticDataFolder(this.tvSolution.SelectedItem as SolutionTreeViewNode))
                {
                    CanContextMenuShow = false;
                    return;
                }
                CanContextMenuShow = true;
                e.Handled = true;
            }
            else
            {
                CanContextMenuShow = false;
            }
        }

        static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
        {
            while (source != null && source.GetType() != typeof(T))
                source = VisualTreeHelper.GetParent(source);

            return source;
        }

        public void Rename_EndEdit(object sender, string newName)
        {
            UIContext.Current.CurrentSolution.UpdateFolderName(UIContext.Current.CurrentSelectedNode.ID, newName);
            UIContext.Current.CurrentSelectedNode.Name = newName;
            SaveSolution(UIContext.Current.LocalWorkSpace.LocalPath, UIContext.Current.CurrentSolution);
        }

        public void SelectItem(Guid id)
        {
            if (tvSolution.SelectedItem != null)
            {
                SolutionTreeViewNode selectedItem = tvSolution.SelectedItem as SolutionTreeViewNode;
                selectedItem.IsSelected = false;
            }
            SolutionTreeViewNode root = tvSolution.Items[0] as SolutionTreeViewNode;

            SelectSubItem(root, id);
        }

        private int SelectSubItem(SolutionTreeViewNode item, Guid id)
        {
            int n = 0;
            for (int i = 0; i < item.Children.Count; i++)
            {
                SolutionTreeViewNode tmp = item.Children[i] as SolutionTreeViewNode;
                if (tmp.ID == id)
                {
                    tmp.IsSelected = true;
                    tmp.IsExpanded = true;
                    break;
                }
                else
                {
                    return SelectSubItem(tmp, id);
                }
            }
            return n;
        }

        private void tvSolution_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            if (!CanContextMenuShow)
            {
                e.Handled = true;
            }
        }
    }
}
